package top.huntwolf.admin.interceptor;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import org.apache.shiro.authz.AuthorizationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import top.huntwolf.admin.pojo.User;
import top.huntwolf.admin.service.UserService;
import top.huntwolf.admin.utils.TokenUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader("token");

        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        //执行认证
        if ("".equals(token)) {
            throw new AuthorizationException("未携带token");
        }
        String open_id;
        try {
            open_id = TokenUtil.getTokenOpenId();
        } catch (JWTDecodeException e) {
            throw new AuthorizationException("获取用户认证发生错误");
        }
        User user = userService.selectUserById(open_id);
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getSessionKey())).build();
        try {
            jwtVerifier.verify(token);
        } catch (JWTVerificationException e) {
            throw new AuthorizationException("认证失败");
        }

        return true;
    }
}
